<template>
  <el-dialog
    v-model="visible"
    :append-to-body="true"
    class="k-dialog-box"
    :class="!hasTitle? 'has-no-title': ''"
    :title="title"
    :width="sizeMap[props.width] ? sizeMap[props.width] : width"
    v-bind="$attrs"
    :before-close="onClickCancel"
  >
    <template #title="slotProps">
      <slot name="title" v-bind="slotProps"></slot>
    </template>
    <el-scrollbar>
      <div v-loading="props.contentLoading" class="dialog-content">
        <slot></slot>
      </div>
    </el-scrollbar>
    <template v-if="props.showFooter" #footer>
      <slot name="footer">
        <div class="dialog-footer">
          <el-button v-if="props.showCancelBtn" :disabled="loading" @click="onClickCancel">{{ props.cancelText }}</el-button>
          <el-button v-if="props.showConfirmBtn" :loading="loading" :disabled="confirmDisabled" type="primary" @click="onClickSubmit">{{ props.confirmText }}</el-button>
        </div>
      </slot>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, computed, useSlots } from 'vue';
defineOptions({ name: 'KDialog' });
interface Props {
  modelValue?: boolean;
  loading?: boolean;
  contentLoading?: boolean;
  title?: string;
  width?: string;
  showFooter?: boolean;
  showCancelBtn?: boolean;
  showConfirmBtn?: boolean;
  beforeClose?: any;
  cancelText?: string;
  confirmText?: string;
  /** 按钮是否禁用，用于禁用表单确认按钮 */
  confirmDisabled?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  contentLoading: false,
  loading: false,
  title: '',
  width: '640px',
  showFooter: true,
  showCancelBtn: true,
  showConfirmBtn: true,
  beforeClose: null,
  cancelText: '取消',
  confirmText: '确定',
  confirmDisabled: false
});
const sizeMap: Record<string, any> = ref({
  xs: '400px',
  small: '500px',
  middle: '640px',
  large: '800px'
});
const hasTitle = computed(() => !!useSlots().title || props.title);
const emits = defineEmits(['submit', 'cancel', 'update:model-value']);

const visible = computed({
  get: () => {
    return props.modelValue;
  },
  set: (val: boolean) => {
    emits('update:model-value', val);
  }
});
const onClickSubmit = () => {
  emits('submit');
};
const onClickCancel = async() => {
  if (props.loading) return;
  if (typeof props.beforeClose === 'function') await props.beforeClose();
  emits('cancel');
  emits('update:model-value', false);
};

</script>

<style lang="scss">
.k-dialog-box {
  .el-dialog {
    &__body {
      padding: 0;
      border-top: 1px solid #dcdfe6;
      border-bottom: 1px solid #dcdfe6;
    }

    &__footer {
      padding-top: 10px;
    }
  }

  .dialog-content {
    box-sizing: border-box;
    min-height: 110px;
    max-height: 56vh;
    padding: 20px;
  }

  &.is-form{
    .dialog-content {
      padding-bottom: 5px;
    }
  }

  .dialog-footer {
    text-align: center;
  }

  &.has-no-title {
    .el-dialog {
      &__headerbtn {
        height: 24px;
      }
    }
  }
}
</style>
